<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../css/elementUI.css">
    <script src="../js/vue.js"></script>
    <script src="../js/axios.js"></script>
    <script src="../js/elementUI.js"></script>

</head>
<body>

<div id="app">

    <el-input v-model="query.name" placeholder="请输入商品名称" clearable style="width: 200px;"></el-input>
    <el-input v-model="query.sn" placeholder="请输入商品货号" clearable style="width: 200px;"></el-input>
    <el-cascader clearable
            v-model="categoryIds"
            :options="options"
            @change="handleChange" style="width: 300px"></el-cascader>

    <el-select v-model="query.brandId" placeholder="请选择" clearable filterable>
        <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
        </el-option>
    </el-select>


    <el-button type="primary" @click="toAdd">添加</el-button>
    <el-button type="danger" @click="delAll">批量删除</el-button>
    <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
        <el-table-column
                type="selection"
                width="55">
        </el-table-column>
        <el-table-column
                prop="spu.id"
                label="编号">
        </el-table-column>
        <el-table-column
                prop="spu.name"
                label="商品名称" >
        </el-table-column>
        <el-table-column
                prop="spu.sn"
                label="货号"
                show-overflow-tooltip>
        </el-table-column>
        <el-table-column
                prop="spu.saleNum"
                label="销量"
                show-overflow-tooltip>
        </el-table-column>
        <el-table-column
                label="上架"
                show-overflow-tooltip>
            <template slot-scope="scope">
                <el-switch
                        v-model="scope.row.spu.isMarketable"
                        active-text="开"
                        inactive-text="关"
                        active-value="1"
                        inactive-value="0"
                        @change="changeIsShowValue(scope.row.spu.id,$event)"
                >
                </el-switch>
            </template>
        </el-table-column>

        <el-table-column
                label="图片">
            <template slot-scope="scope">
                <img :src="scope.row.spu.image" alt="" width="100px">
            </template>
        </el-table-column>
        <el-table-column label="SKU库存">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        @click="toEditSkuList(scope.$index, scope.row)">修改库存</el-button>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>

    </el-table>

    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="query.page"
            :page-sizes="[10, 20, 30,40]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>


    <el-dialog title="编辑货品信息" :visible.sync="dialogTableVisible" width="90%">
        <el-table :data="skuList">
            <el-table-column label="货号" width="150">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.sn" clearable></el-input>
                </template>
            </el-table-column>


            <el-table-column :label="n" width="150" v-for="(n,i) in specNames" :key="i">
                <template slot-scope="scope">
                    {{dataArr[scope.$index][i]}}
                </template>
            </el-table-column>


            <el-table-column label="价格（分）" width="150">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.price" clearable></el-input>
                </template>
            </el-table-column>
            <el-table-column label="库存" width="150">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.num" clearable></el-input>
                </template>
            </el-table-column>
            <el-table-column label="预警库存" width="150">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.alertNum" clearable></el-input>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="editSkuInfo">确 定</el-button>
        </div>
    </el-dialog>


    <el-dialog :title="mode.title+'商品'" :visible.sync="dialogFormVisible" top="10px" :before-close="beforeCloseDialog">
        <el-form :model="form">
            <el-form-item label="名称" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="首字母" :label-width="formLabelWidth">
                <el-input v-model="form.letter" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="排序" :label-width="formLabelWidth">
                <el-input v-model="form.seq" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="图片" :label-width="formLabelWidth">
                <el-upload
                        action="/upload/uploadOss.do"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :on-success="uploadSuccess"
                        :file-list="fileList"
                >
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" append-to-body>
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addBrand">确 定</el-button>
        </div>
    </el-dialog>

</div>

</body>
<script>
    new Vue({
        el: "#app",
        data: {
            currentGoods:{},
            specNames:[],
            dataArr:[],
            dialogTableVisible:false,
            skuList:[],
            mode:{
                title:"",
                url:""
            },
            fileList:[],
            formLabelWidth:"120px",
            query:{
                name:"P900",
                brandId:"",
                page:1,
                size:10
            },
            form:{
                image:"",
                name:"",
                seq:"",
                letter:""
            },
            tableData:[],
            total:0,
            multipleSelection:[],
            dialogImageUrl: '',
            dialogVisible: false,
            dialogFormVisible:false,

            brandId:"",
            categoryList:[],//代表所有的分类集合
            categoryIds: [],//三级联动选中的分类id集合
            options: [],//三级联动的数据集合
            brandList:[]
        },
        watch:{
            query:{
                deep:true,
                handler(){
                    this.initData()
                }
            }
        },
        methods: {
            editSkuInfo(){
                axios.post(`/spu/editSkuInfo.do`,this.skuList).then(res=>{
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.currentGoods.skuList = this.skuList;
                    this.dialogTableVisible = false;
                })
            },
            toEditSkuList(index,row){
                this.currentGoods = row;
                this.skuList = JSON.parse(JSON.stringify(row.skuList));

                var specNames = [];
                var spu = row.spu;
                var specItems = JSON.parse(spu.specItems);
                for (var key in specItems) {
                    specNames.push(key);
                }

                var dataArr = [];

                for (let i = 0; i < this.skuList.length; i++) {
                    var skuPara = [];
                    var skuSpec = JSON.parse(this.skuList[i].spec);
                    for (let j = 0; j < specNames.length ; j++) {
                        skuPara.push(skuSpec[specNames[j]])
                    }
                    dataArr.push(skuPara)
                }
                this.dataArr = dataArr;
                this.specNames = specNames;

                this.dialogTableVisible = true;
            },
            handleChange(value) {
                this.brandList = [];
                if(value&&value.length!=0){
                    axios.get(`/categoryBrand/findBrandByCategoryIdByMybatisXml.do?categoryId=${value[2]}`).then(res=>{
                        this.brandList = res.data;
                    })
                    this.query.category1Id = value[0]
                    this.query.category2Id = value[1]
                    this.query.category3Id = value[2]
                    this.initData();
                }else{
                    this.query.brandId = ""
                    this.query.category1Id = ""
                    this.query.category2Id = ""
                    this.query.category3Id = ""
                    this.initData();
                }

            },
            changeIsShowValue(id,v){
                var obj = {
                    id:id,
                    isMarketable:v
                }
                axios.post(`/spu/changeGoodsMarketable.do`,obj).then(res=>{
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                })
            },
            handleEdit(index, row) {
                location.href = "goodsEdit.html?id="+row.spu.id;
            },
            delAll(){
                if(this.multipleSelection.length>0){
                    this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.delBrand(this.multipleSelection.map(m=>m.id).join(","));
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }else{
                    this.$message('请选择一条数据');
                }
            },
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.delBrand(row.id);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            delBrand(ids){
                axios.get(`/spu/deleteAll.do?ids=${ids}`).then(res=>{
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.initData()
                })

            },
            beforeCloseDialog(close){

                this.initFormData();
                close()//关闭弹窗的方法
            },
            addBrand(){
                axios.post(this.mode.url,this.form).then(res=>{
                    this.initFormData();
                    this.initData()
                })
            },
            toAdd(){
                location.href = "goodsAdd.html"
            },
            initFormData(){
                this.form = {
                    image:"",
                    name:"",
                    seq:"",
                    letter:""
                }
                this.fileList = [];
                this.dialogFormVisible = false;

            },
            initData(){
                axios.post(`/spu/findPage.do?page=${this.query.page}&size=${this.query.size}`,this.query).then(res=>{
                    this.tableData = res.data.rows;
                    this.total = res.data.total;
                    if(this.tableData.length==0&&this.query.page>1){
                        this.query.page--
                    }
                })

            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.query.size = val
            },
            handleCurrentChange(val) {
                this.query.page = val
            },
            handleRemove(file, fileList) {
                this.form.image = "";
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            uploadSuccess(res){
                this.form.image = res;
            },
            initCategoryList(){
                axios.get(`/category/findAll.do`).then(res=>{
                    this.categoryList = res.data;
                    var total = this.findCategoryByPid(0);
                    for (let i = 0; i < total.length; i++) {
                        var one = total[i];
                        one.children = this.findCategoryByPid(one.value);
                        for (let j = 0; j < one.children.length; j++) {
                            var two = one.children[j];
                            two.children = this.findCategoryByPid(two.value);
                        }
                    }
                    this.options = total;

                })
            },
            findCategoryByPid(pid){
                var arr = [];
                for (let i = 0; i < this.categoryList.length; i++) {
                    var category = this.categoryList[i];
                    if(category.parentId==pid){
                        var obj = {
                            value:category.id,
                            label:category.name
                        }
                        arr.push(obj)
                    }
                }
                return arr
            }
        },
        created() {
            this.initCategoryList();
            this.initData();
        }
    })
</script>
</html>